package com.yl.chainStore.common.handler

import com.alibaba.fastjson.JSONObject
import com.yl.chainStore.services.ICustomerInfoService
import com.yl.common.UserType
import com.yl.common.utils.ApplicationContextUtil
import com.yl.message.service.ISendMessageService
import com.yl.message.vo.ToUserMessageVo
import com.yl.users.services.ICompanyUserService
import org.slf4j.LoggerFactory
import org.springframework.boot.ApplicationArguments
import org.springframework.boot.ApplicationRunner
import org.springframework.context.annotation.DependsOn
import org.springframework.core.annotation.Order
import org.springframework.stereotype.Component
import java.util.concurrent.LinkedBlockingQueue

/**
 * 队列处理
 */
@Component
@DependsOn("applicationContextUtil")
class SendMessageHandler : ApplicationRunner {

	companion object {
		private val log = LoggerFactory.getLogger(SendMessageHandler::class.java)!!

		val messages = LinkedBlockingQueue<ToUserMessageVo>()

		private val sendMessageService = ApplicationContextUtil.getBean("sendMessageService") as ISendMessageService

		private val iCustomerInfoService =
			ApplicationContextUtil.getBean("iCustomerInfoService") as ICustomerInfoService

		private val iCompanyUserService = ApplicationContextUtil.getBean("iCompanyUserService") as ICompanyUserService

	}

	override fun run(args: ApplicationArguments?) {
		while (true) {
			try {
				if (messages.isEmpty()) {
					Thread.sleep(1000)
				}
				val message = messages.take()
				log.info("发送信息 ==> message:", message)
				if (message.userType == UserType.Custom) {
					sendMessageService.sendMessageToCustom(
						message,
						::customerSendNoticeConfig
					)
				} else if (message.userType == UserType.Company) {
					sendMessageService.sendMessageToCustom(message,
						::companyUserSendNoticeConfig)
				}
			} catch (e: Exception) {
				e.printStackTrace()
			}
		}
	}

	private fun customerSendNoticeConfig(companyId: Long, userId: Long, name: String): JSONObject? {
		return iCustomerInfoService.sendNoticeConfig(companyId, userId, name)
	}

	private fun companyUserSendNoticeConfig(companyId: Long, userId: Long, name: String): JSONObject? {
		return iCompanyUserService.sendNoticeConfig(companyId, userId, name)
	}
}
